package net.xdclass.util;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.exception.BizException;
import net.xdclass.model.LoginUser;

import java.util.Date;

/**
 * @Description:
 * @author : xuezhen
 * @CreateDate:2021/4/14 22:00
 * @UpdateUser:
 * @UpdateDate:
 * @UpdateRemark:
 * @Version:v2.0
 */
@Slf4j
public class JWTUtil {

    /**
     * token过期时间10天
     */
    public static final long EXPIRE = 1000 * 60 * 60 * 10 * 24;

    /**
     * 加密的秘钥
     */
    public static final String SECRET = "my.secret";

    /**
     * 令牌的前缀
     */
    public static final  String TOKEN_PERFIX = "my.token.perfix";

    /**
     * subject
     */
    public static final String SUBJECT = "xdclass";


    /**
     * 根据用户信息生成token令牌
     * @param loginUser
     * @return
     */
    public static  String generatorJsonWebToken(LoginUser loginUser){
        if(loginUser == null){
            throw new BizException(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                // payoad
                .claim("head_image", loginUser.getHeadImg())
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("mail", loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PERFIX+token;
        return token;
    }


    /**
     * 校验token方法
     * @param token token
     * @return
     */
    public static Claims checkJsonWebToken(String token){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PERFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            log.error("JWT token 解析失败:",e);
            return null;
        }
    }
}
